<script lang="ts" setup>
import type { QualificationOptionType } from '@/api/userInfo'
import { saveQualification } from '@/api/userInfo'
import { uploadTempFileUrl } from '@/api/common'
import { getAccessToken } from '@/utils/auth'
import { useToast } from 'wot-design-uni'
// import {useUpload} from '@/utils/uploadFile'

defineOptions({ name: 'PopCertificateForm' })
const emit = defineEmits(['refresh'])
const toast = useToast()
const show = ref(false)
const form_ref = ref()
const model = reactive<{
  qualificationName: string,
  fileList: Array<any>
}>({
  qualificationName: '',
  fileList: []
})
const rules = {
  qualificationName: [
    {
      required: true,
      message: '请输入证书名称',
      // validator: (value) => {
      //   if (value && value.length > 6) {
      //     return Promise.resolve()
      //   }
      //   else {
      //     return Promise.reject('请输入完工描述')
      //   }
      // },
    },
  ],
  fileList: [
    {
      required: false,
      message: '请上传证书图片',
      validator: (value) => {
        if (Array.isArray(value) && value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject()
        }
      },
    },
  ],
}
// const fileList = ref([])
const qualificationOption = ref<QualificationOptionType | null>()
const open = (option: QualificationOptionType) => {
  qualificationOption.value = option
  show.value = true
}

const handleClose = () => {
  model.fileList = []
  model.qualificationName = ''
  show.value = false
}
const submit = () => {
  form_ref.value.validate().then(async ({ valid, errors }) => {
    if (valid) {
      const {qualificationType} = qualificationOption.value
      const {qualificationName} = model
      const file = JSON.parse(model.fileList[0].response)
      const qualificationPath = file.data
      const dataParam = {
        qualificationType,
        qualificationFileReqVoList: [
          {
            qualificationName,
            qualificationPath,
          },
        ],
      }
      const res = await saveQualification(dataParam)
      if(res.code === 0) {
        toast.success({ msg: '上传成功！' })
        setTimeout(() => {
          handleClose()
          emit('refresh')
        }, 500);
      }
    }
  })
}
const customUpload = (file, formData, options) => {
  const uploadTask = uni.uploadFile({
    url: uploadTempFileUrl,
    header: {
      Authorization: `Bearer ${getAccessToken()}`,
    },
    name: options.name,
    fileName: options.name,
    fileType: options.fileType,
    formData,
    filePath: file.url,
    success(res) {
      if (res.statusCode === options.statusCode) {
        options.onSuccess(res, file, formData)
      } else {
        options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
      }
    },
    fail(err) {
      // 设置上传失败
      options.onError(err, file, formData)
    },
  })
  // 设置当前文件加载的百分比
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

// const { loading, data, run } = useUpload<string>({ user: '菲鸽' })
defineExpose({
  open,
})
</script>

<template>
  <JediPagePop
    v-model="show"
    title="证书上传"
    custom-class="bgGray"
    @close="handleClose"
  >
    <wd-notice-bar
      v-if="qualificationOption"
      :text="qualificationOption.description"
      prefix="warn-bold"
      :scrollable="false"
    />
    <view class="m-2">
      <wd-form ref="form_ref" :model="model" :rules="rules">
        <wd-cell-group border>
          <wd-input
            v-model="model.qualificationName"
            label="证书名称"
            label-width="100px"
            prop="qualificationName"
            clearable
            :maxlength="10"
            placeholder="请输入证书名称"
          />
          <wd-cell title="" title-width="0" custom-class="noTitle" prop="fileList">
            <wd-upload
              v-model:file-list="model.fileList"
              :limit="1"
              :upload-method="customUpload"
            />
          </wd-cell>
          <wd-cell title-width="0px">
            <view class="footer">
              <wd-button block size="large" @click="submit"> 保存 </wd-button>
            </view>
          </wd-cell>
        </wd-cell-group>
      </wd-form>
    </view>
    <!-- <template #footer>
      <wd-button block size="large"> 保存 </wd-button>
    </template> -->
  </JediPagePop>
</template>
